package coe.pumbaa

import org.springframework.dao.DataIntegrityViolationException
import grails.plugins.springsecurity.Secured

class CategoryController {

    static allowedMethods = [save: "POST", update: "POST"]
    def stringManagerService
    def authenticationManagerService
    def springSecurityService
    
    def index() {
        redirect(action: "list", params: params)
    }

    def list() {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        def user = springSecurityService.currentUser
        def categoryInstanceList = authenticationManagerService.getCategoriesList(user, params)
        
        def pos = (authenticationManagerService.isAdmin(user))?"manage_category":"category"
        [categoryInstanceList: categoryInstanceList.list, categoryInstanceTotal: categoryInstanceList.count, navigation:[pos:pos]]
    }

    @Secured(['IS_AUTHENTICATED_REMEMBERED'])
    def create() {
        if(springSecurityService.currentUser.role.level <= 1){
            [categoryInstance: new Category(params), navigation:[pos:"manage_category"]]
        }else{
            flash.warning = "You are not admin or staff."
            redirect(controller:'home',action:'index')
        }
    }

    @Secured(['IS_AUTHENTICATED_REMEMBERED'])
    def save() {
        if(springSecurityService.currentUser.role.level <= 1){
            def categoryInstance = new Category(params)
            categoryInstance.allowView = (String)Role.findByType("admin").id
            categoryInstance.allowPost = (String)Role.findByType("admin").id
            params.allowViewList.each{
                categoryInstance.allowView = stringManagerService.addObjectInToString(Role.get(it),categoryInstance.allowView)
            }
            params.allowPostList.each{
                categoryInstance.allowPost = stringManagerService.addObjectInToString(Role.get(it),categoryInstance.allowPost)
                categoryInstance.allowView = stringManagerService.addObjectInToString(Role.get(it),categoryInstance.allowView)
            }
            if (!categoryInstance.save(flush: true)) {
                render(view: "create", model: [categoryInstance: categoryInstance], navigation:[pos:"manage_category"])
                return
            }

            flash.success = message(code: 'default.created.message', args: [message(code: 'category.label', default: 'Category'), categoryInstance.id])
            redirect(action: "list")
        }else{
            flash.warning = "You are not admin or staff."
            redirect(controller:'home',action:'index')
        }
    }

    @Secured(['IS_AUTHENTICATED_REMEMBERED'])
    def edit() {
        if(springSecurityService.currentUser.role.level <= 1){
            def categoryInstance = Category.get(params.id)
            if (!categoryInstance) {
                flash.error = message(code: 'default.not.found.message', args: [message(code: 'category.label', default: 'Category'), params.id])
                redirect(action: "list")
                return
            }

            [categoryInstance: categoryInstance, navigation:[pos:"manage_category"]]
        }else{
            flash.warning = "You are not admin or staff."
            redirect(controller:'home',action:'index')
        }
    }

    @Secured(['IS_AUTHENTICATED_REMEMBERED'])
    def update() {
        if(springSecurityService.currentUser.role.level <= 1){
            def categoryInstance = Category.get(params.id)
            if (!categoryInstance) {
                flash.error = message(code: 'default.not.found.message', args: [message(code: 'category.label', default: 'Category'), params.id])
                redirect(action: "list")
                return
            }
        
            if (params.version) {
                def version = params.version.toLong()
                if (categoryInstance.version > version) {
                    categoryInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                        [message(code: 'category.label', default: 'Category')] as Object[],
                          "Another user has updated this Category while you were editing")
                    render(view: "edit", model: [categoryInstance: categoryInstance, navigation:[pos:"manage_category"]])
                    return
                }
            }

            categoryInstance.properties = params
            categoryInstance.allowView = (String)Role.findByType("admin").id
            categoryInstance.allowPost = (String)Role.findByType("admin").id
            params.allowViewList.each{
                categoryInstance.allowView = stringManagerService.addObjectInToString(Role.get(it),categoryInstance.allowView)
            }
            params.allowPostList.each{
                categoryInstance.allowPost = stringManagerService.addObjectInToString(Role.get(it),categoryInstance.allowPost)
                categoryInstance.allowView = stringManagerService.addObjectInToString(Role.get(it),categoryInstance.allowView)
            }
            if (!categoryInstance.save(flush: true)) {
                flash.error = "Error! Check your input."
                render(view: "edit", model: [categoryInstance: categoryInstance, navigation:[pos:"manage_category"]])
                return
            }

            flash.success = message(code: 'default.updated.message', args: [message(code: 'category.label', default: 'Category'), categoryInstance.id])
            redirect(action: "list")
        }else{
            flash.warning = "You are not admin or staff."
            redirect(controller:'home',action:'index')
        }
    }

    @Secured(['IS_AUTHENTICATED_REMEMBERED'])
    def delete() {
        if(springSecurityService.currentUser.role.level <= 1){
            def categoryInstance = Category.get(params.id)
            if (!categoryInstance) {
                flash.error = message(code: 'default.not.found.message', args: [message(code: 'category.label', default: 'Category'), params.id])
                redirect(action: "list")
                return
            }

            try {
                categoryInstance.delete(flush: true)
                flash.success = message(code: 'default.deleted.message', args: [message(code: 'category.label', default: 'Category'), params.id])
                redirect(action: "list")
                return
            }
            catch (DataIntegrityViolationException e) {
                flash.error = message(code: 'default.not.deleted.message', args: [message(code: 'category.label', default: 'Category'), params.id])
                redirect(action: "list")
                return
            }
        }else{
            flash.warning = "You are not admin or staff."
            redirect(controller:'home',action:'index')
        }
    }
}
